//
//  LoadDetailsViewController.m
//  CreditHub
//
//  Created by chenglang on 2024/9/18.
//

#import "LoadDetailsViewController.h"
#import "LoadDetailsHeaderCell.h"
#import "LoadDetailsCerTableViewCell.h"
#import "HomeRequest.h"
#import "DetailCerCardViewController.h"
#import "DetailPersonalInfoVC.h"
#import "DetailContactInfoVC.h"
#import "WebViewController.h"
#import "UUID.h"

@interface LoadDetailsViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSDictionary *pity;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *layoutHeight;
@end

@implementation LoadDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.pointType = @"10";
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"LoadDetailsHeaderCell" bundle:nil] forCellReuseIdentifier:@"LoadDetailsHeaderCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"LoadDetailsCerTableViewCell" bundle:nil] forCellReuseIdentifier:@"LoadDetailsCerTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"LoanMterialsStepCell" bundle:nil] forCellReuseIdentifier:@"LoanMterialsStepCell"];
    self.tableView.estimatedRowHeight = 44;
    self.layoutHeight.constant = 150+SYS_TopHeight;
    
    self.buttonNext.hidden = YES;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self requestDetail];
}

- (void)requestDetail{
    __weak typeof(self) weakSelf = self;
    [HomeRequest requestLoadDetailseId:self.detailId success:^(NSURLSessionDataTask *task, id response) {
        if([response[@"ofexcitement"] integerValue] == 0){
            weakSelf.pity = [NSDictionary dictionaryWithDictionary:response[@"pity"]];
            weakSelf.ch_title = CHString(weakSelf.pity[@"topump"][@"noise"]);
            weakSelf.buttonNext.hidden = NO;
            if(!CHStringIsEmpty(weakSelf.pity[@"topump"][@"furry"])){
                [weakSelf.buttonNext setTitle:weakSelf.pity[@"topump"][@"furry"] forState:UIControlStateNormal];
            }
            
            NSDictionary *dicAgree = [NSDictionary dictionaryWithDictionary:weakSelf.pity[@"obstinate"]];
            
            if(!CHStringIsEmpty(dicAgree[@"feeling"])){
                weakSelf.buttonAgree.hidden = NO;
                weakSelf.buttonPrivacy.hidden = NO;
                [weakSelf.buttonAgree setTitle:dicAgree[@"outside"] forState:UIControlStateNormal];
            }
            [weakSelf.tableView reloadData];
        }else{
            xhl_showMessage(response[@"shared"] );
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}

- (void)requestPlaceOrder{
    
    xhl_hudLoading();
    NSDictionary *topump = [NSDictionary dictionaryWithDictionary:self.pity[@"topump"]];
    __weak typeof(self) weakSelf = self;
    [HomeRequest requestPlaceOrderId:CHString(topump[@"astounded"]) amount:CHString(topump[@"guess"]) limitDate:CHString(topump[@"behind"]) type:CHString(topump[@"left"])  success:^(NSURLSessionDataTask *task, id response) {
        if([response[@"ofexcitement"] integerValue] == 0){

            NSString *url = response[@"pity"][@"faint"];
            WebViewController *webVC = [[WebViewController alloc] init];
            webVC.url = [weakSelf getRequestUrlString:url];
            webVC.backRoot =1;
            [weakSelf.navigationController pushViewController:webVC animated:YES];
            
            weakSelf.orderNo = CHString(topump[@"astounded"]);
            weakSelf.endTime = [BaseService getTimeStringSince1970];
            weakSelf.startTime = [BaseService getTimeStringSince1970];
            [weakSelf requestUploadPointType];
        }
        xhl_showMessage(response[@"shared"]);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        xhl_hudDismiss();
    }];
}
- (NSString *)getRequestUrlString:(NSString *)str {
    
    NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    
    NSString *url= [NSString stringWithFormat:@"%@&areal=%@&boo=%@&howling=%@&ear=%@&knew=%@&minute=%@&which=1",str,[UserInfoModel getUserInfo].areal,appVersion,[BaseService friendlyDeviceName],[UUID getUUID],[[UIDevice currentDevice] systemVersion],[BaseService getIDFA]];
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet];
    return url;
}

- (IBAction)clickAgree:(id)sender {
    self.buttonAgree.selected = !self.buttonAgree.selected;
}
- (IBAction)clickPrivacy:(id)sender {
    
    NSDictionary *dicAgree = [NSDictionary dictionaryWithDictionary:self.pity[@"obstinate"]];
    
    if(!CHStringIsEmpty(dicAgree[@"feeling"])){
        WebViewController *webVC = [[WebViewController alloc] init];
        webVC.url = dicAgree[@"feeling"];
        [self.navigationController pushViewController:webVC animated:YES];
    }
}
- (IBAction)clickLoan:(id)sender {
    
    if( [self.pity[@"truthfully"] isKindOfClass:[NSDictionary class]] ){
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:self.pity[@"truthfully"]];
        [self nextClickType:dicInfo[@"till"]];
    }else{
        if(!self.buttonAgree.selected){
            xhl_showMessage(@"Please read and agree to the agreement first");
            return;
        }
        [self requestPlaceOrder];
    }
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if(self.pity.count == 0){
        return 0;
    }
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.row ==1){
        LoadDetailsCerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LoadDetailsCerTableViewCell"];
        __weak typeof(self) weakSelf = self;
        [cell showList:[NSArray arrayWithArray:self.pity[@"sounded"]] block:^(NSDictionary * _Nonnull dicInfo) {
            
            if( [dicInfo[@"camping"] integerValue] == 1 ){
                [weakSelf nextClickType:dicInfo[@"till"]];
            }else{
                [weakSelf clickLoan:nil];
            }
            
        }];
        return cell;
    }
    
    LoadDetailsHeaderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LoadDetailsHeaderCell"];
    cell.dicInfo = self.pity[@"topump"];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row==1){
        return UITableViewAutomaticDimension;
    }
    return 210;
    
}

- (void)nextClickType:(NSString *)till{

    if([CHString(till) isEqualToString:@"shared"]){
        DetailCerCardViewController *vc = [[DetailCerCardViewController alloc] init];
        vc.lightat = self.detailId;
        [self.navigationController pushViewController:vc animated:YES];
    }else if([CHString(till) isEqualToString:@"pity"] || [CHString(till) isEqualToString:@"which"] || [CHString(till) isEqualToString:@"shall"]){
        DetailPersonalInfoVC *vc = [[DetailPersonalInfoVC alloc] init];
        vc.detailId = self.detailId;
        if([CHString(till) isEqualToString:@"pity"]){
            vc.type = 1;
        }else if ( [CHString(till) isEqualToString:@"which"]){
            vc.type = 2;
        }else if([CHString(till) isEqualToString:@"shall"]){
            vc.type = 3;
        }
        [self.navigationController pushViewController:vc animated:YES];
    }else if([CHString(till) isEqualToString:@"asleep"]){
        
        DetailContactInfoVC *vc = [[DetailContactInfoVC alloc] init];
        vc.detailId = self.detailId;
        [self.navigationController pushViewController:vc animated:YES];
    }
//    InfoTextInputView
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
